/*------------------------------------------------------------------------------*\
**   Copyright 2008-2009 Jonhnny Weslley                                        **
**                                                                              **
**   Licensed under the Apache License, Version 2.0 (the "License");            **
**   you may not use this file except in compliance with the License.           **
**   You may obtain a copy of the License at                                    **
**                                                                              **
**       http://www.apache.org/licenses/LICENSE-2.0                             **
**                                                                              **
**   Unless required by applicable law or agreed to in writing, software        **
**   distributed under the License is distributed on an "AS IS" BASIS,          **
**   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   **
**   See the License for the specific language governing permissions and        **
**   limitations under the License.                                             **
\*------------------------------------------------------------------------------*/

package org.scalashell.terminal

trait Renderer extends org.scalashell.util.StringReplacer {

  import ANSI.Code._

  val beginToken = "@|"
  val endToken = "|"

  private val CODE_TEXT_SEPARATOR  = " "
  private val CODE_LIST_SEPARATOR  = ","

  def isRenderable(text: String) = text != null && text.indexOf(beginToken) >= 0

  def render(text: String) = replace(text)

  def evaluate(text: String) = {
    val i = text indexOf CODE_TEXT_SEPARATOR
    if (i < 0) {
      throw new RenderException("Missing ANSI code/text separator '" + CODE_TEXT_SEPARATOR + "': " + text)
    }

    val buffer = ANSI.buffer
    val tmp = text.substring(0, i)
    val codes = tmp split CODE_LIST_SEPARATOR
    val plaintext = text.substring(i + 1, text.length)

    codes foreach (buffer attrib _)
    buffer append plaintext
    buffer attrib OFF
    buffer.toString
  }

}

class RenderException(message: String) extends Exception(message)

